﻿using System;
using System.Windows.Forms;
using MapWindow.Map;
using MapWindow.Components;
using MapWindow.PluginInterfaces;
using MapWindow.Data;

namespace AddDataPlugin
{
    /// <summary>
    /// This MapWindow 6 plug-in demonstrates how to add data to the map
    /// </summary>
    [MapWindowPlugin("AddDataPlugin", Author="JK", UniqueName="AddDataPlugin_1", Version="1.0")]
    public class Class1 : Extension, IMapPlugin
    {
        #region Variables

        //the class level variable for accessing the main application
        private IMapPluginArgs _mapWin;

        //the menu item added by the plug-in
        private ToolStripMenuItem menuItem1;

        #endregion

        #region IMapPlugin Members

        //when the plug-in is activated
        public void Initialize(IMapPluginArgs args)
        {
            _mapWin = args;
            
            //add a new menu item
            menuItem1 = new ToolStripMenuItem("Add Data");
            //add a sub-menu item
            ToolStripMenuItem menuItem2 = new ToolStripMenuItem("Add data to map");
            menuItem1.DropDownItems.Add(menuItem2);
            _mapWin.MainMenu.Items.Add(menuItem1);

            //handle the menu item click event
            menuItem2.Click += new EventHandler(menuItem2_Click);
        }
        
        #endregion

        #region Extension Members

        //when the plug-in is deactivated
        protected override void OnDeactivate()
        {
            //remove the menu item
            if (_mapWin.MainMenu.Items.Contains(menuItem1))
            {
                _mapWin.MainMenu.Items.Remove(menuItem1);
            }
        }

        #endregion

        #region Event Handlers

        //when the menu item is clicked
        void menuItem2_Click(object sender, EventArgs e)
        {
            //show a file dialog
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "Select a shapefile";
            ofd.Filter = "Shapefiles|*.shp";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                //to add a new layer to the map
                FeatureSet fs = new FeatureSet();
                fs.Open(ofd.FileName);
                _mapWin.Map.Layers.Add(fs);
            }
        }

        //This function opens a shapefile and adds it to the map
        private void AddShapefileToMap(string fileName)
        {
            FeatureSet fs = new FeatureSet();
            fs.Open(fileName);
            _mapWin.Map.Layers.Add(fs);
        }

        #endregion
    }
}
